#include <stdio.h>
#include <errno.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>

#include <elog.h>

#include <input_kbdrv.hpp>
#include <inputmanager.hpp>
#include <inputdrv_manage.hpp>

#include <autoinit.hpp>

#include <iostream>
#include <boost/thread.hpp>
using namespace std;

// UTF-8


static input_event_listener_t  key_event_listener;
 
static int          g_fd;  
static int          key_driver_is_init=0;
static key_board_handle key_board_func;

int key_board_init(key_board_handle event_listener)
{
	if(!key_driver_is_init)
	{
	   g_fd = open("/dev/IIC_key", O_RDWR);
	   if(g_fd < 0)
	   {
		perror("open /dev/IIC_key error");
		return -1;
	   }
	   key_driver_is_init = 1;
	}

	key_board_func = event_listener;

	return 0;
} 


int key_board_close(void)
{
	if(g_fd<0)
		return -1;
	close(g_fd);
	key_driver_is_init=0;
	key_board_func = NULL;
	//如果您没有支持C ++ 11的最新gcc，请尝试使用NULL而不是nullptr。  GB2312     
}


static unsigned char keycode_paralyse(int keyvalue){
        if(16 == keyvalue)
            return  Key_Code_0;
        if(4 == keyvalue)
            return  Key_Code_1;
        if(9 == keyvalue)
            return  Key_Code_2;
        if(10 == keyvalue)
            return  Key_Code_3;
        if(3 == keyvalue)
            return  Key_Code_4;
        if(11 == keyvalue)
            return  Key_Code_5;
        if(12 == keyvalue)
            return  Key_Code_6;
        if(2 == keyvalue)
            return  Key_Code_7;
        if(13 == keyvalue)
            return  Key_Code_8;
        if(14 == keyvalue)
            return  Key_Code_9;
        if(1 == keyvalue)
            return  Key_Code_ChangeMode;
        if(15 == keyvalue)
            return  Key_Code_OK;  
		
        return 0;
}


int key_wait_read(void)
{
	unsigned char keyval = 0;
	int ret=0; 
	int key_code = 0;
	int key_value = 0;

	if(key_board_func == NULL)
	   return -1;

	ret=read(g_fd, &keyval, 1);
	key_code  = keyval;
	key_value = ret;

	key_code = keycode_paralyse(keyval);
	if(!key_code)
		return -1;

	(key_board_func)(key_code,key_value);

	return 0;
}


static void keyboard_func(int key_code, int key_value)
{
	static struct input_event event = {0};

    event.type = EV_KEY;
    event.code = key_code;       
    event.value = key_value;

	//cout << "APP key_value :"  <<  key_value << endl;

    key_event_listener = input_manager_drv_get_event_listener(key_inputdev_type);

    //回调上层应用注册的事件上报方法: 对应input_key.c内的 key_input_event_listener()
    key_event_listener(key_inputdev_type, &event);
}


static void thread_run(const int &id)
{
	key_board_init(keyboard_func);	

	while(1)
    {
        key_wait_read();
    }
}


static void drv_input_key_init(void)
{
	boost::thread t1(thread_run, 0);
	t1.detach();

    return;
}


auto_dev_init(drv_input_key_init);


